<template>
  <div id="youngcadres">
    <el-dialog
      :title="dialogtitle"
      :visible.sync="dialogVisible"
      width="98%" top="20px" :close-on-click-modal="false" :close-on-press-escape="false">
      <personEdit @dialogHide="dialogHide($event)" :state="$route.params.state" :personId="personId" :passStep="passStep" :readOnly="readonly" :timestamp="timestamp" :showDept="false" :Formal="false"></personEdit>
    </el-dialog>
    <el-dialog
      title="入库依据"
      :visible.sync="rkyjVisible"
      width="98%" top="20px" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :model="rkyjForm" label-width="100px" ref="rkyjForm" :rules="rkyjFormRules">
        <el-form-item label="提示">
          目前 <b>{{unWritePersons.join('、')}}</b> 等 <b>{{unWritePersons.length}}</b> 人未填写入库依据，请填写以上 <b>{{unWritePersons.length}}</b> 人的入库依据
        </el-form-item>
        <el-form-item prop="rkyj" label="入库依据">
          <el-autocomplete :trigger-on-focus="true" :fetch-suggestions="querySearch" v-model="rkyjForm.rkyj" style="width:100%" :maxlength="500"></el-autocomplete>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click.native="rkyjSubmit(false)" :loading="rkyjloading">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/' }">系统首页</el-breadcrumb-item>
      <!-- <el-breadcrumb-item>人才建设</el-breadcrumb-item> -->
      <el-breadcrumb-item :to="{ path: '/youngCadres/yearlist' }">优秀年轻干部</el-breadcrumb-item>
      <el-breadcrumb-item :to="handleClick($route.params.theYear)">{{ $route.params.theYear + '年' }}</el-breadcrumb-item>
      <el-breadcrumb-item >{{ inRoles('ROLE_banshirenyuan') ? '初审' : '审查' }}</el-breadcrumb-item>
    </el-breadcrumb>
    <section class="wboxs">
    <!--工具条-->
      <h1>优秀年轻干部</h1>
      <el-form :inline="true">
        <div style="padding:22px 22px 0;">

          <el-button type="success" @click="backUnitList" icon="el-icon-back">返回</el-button>
          <el-form-item label="单位名称" label-width="90px">
            <b>{{unitname}}</b><span v-if="$route.params.state===2"> （已审查完成信息）</span>
          </el-form-item>
          <div style="float:right;">
            <el-button-group v-if="$route.params.state!==2&&this.ids&&this.ids.length>0">
              <el-tooltip class="item" effect="dark" content="上移" placement="top">
                <el-button @click="setOrder(1)" icon="el-icon-arrow-up" type="danger" :loading="orderloading" :disabled="this.ids.length>0&&this.ids[0].id===this.list[0].id&&pageNum===1"></el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="下移" placement="top">
                <el-button @click="setOrder(2)" icon="el-icon-arrow-down" type="danger" :loading="orderloading" :disabled="this.ids.length>0&&this.ids[0].id===this.list[this.list.length-1].id&&pageNum===parseInt(totalPage)"></el-button>
              </el-tooltip>
            </el-button-group>
            <el-popconfirm :title="'确定退回'+(this.ids && this.ids.length > 0?'所选':'全部')+'信息吗？'" v-if="passStep===1" @confirm="sendback()">
              <el-button slot="reference" type="warning" icon="el-icon-s-fold">退回</el-button>
            </el-popconfirm>
            <el-popconfirm :title="'确定完成'+passStepText+'吗？'" @confirm="passed()" v-if="$route.params.state!==2">
              <el-button slot="reference" type="success" icon="el-icon-success">{{passStepText}}完成{{passStep===2?'并入库':''}}</el-button>
            </el-popconfirm>
          </div>
        </div>
      </el-form>
    </section>
    <section class="wboxd" style="margin-top:10px">
      <!--列表-->
      <el-table :data="list" highlight-current-row v-loading="listLoading" style="width: 100%;" @sort-change='sortChange' :height="tableHeight" border
        @selection-change="handleSelectionChange"
        ref="multipleTable" :row-class-name="tableRowClassName"
        >
        <el-table-column type="index" label="序号" width="50" fixed align="center" class-name="tableth" :index="indexMethod">
        </el-table-column>
        <el-table-column type="selection" width="45" fixed>
        </el-table-column>
        <el-table-column prop="xm" label="姓名" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="sfzh" label="身份证号" width="180" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="isOverAge" label="超出年龄范围" width="140" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span :class="{'red-bold': scope.row.isOverAge === 1}">
              {{ scope.row.isOverAge === 1 ? '是' : scope.row.isOverAge === 2 ?'否' : '' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="zzmm" label="政治面貌" width="130" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{scope.row.zzmmText}}
          </template>
        </el-table-column>
        <el-table-column prop="cjgzsj" label="参加工作时间" width="130" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
          {{formatDate(scope.row.cjgzsj)}}
          </template>
        </el-table-column>
        <el-table-column prop="finishFlag" label="审核状态" width="90" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <template v-if="passStep===1">{{scope.row.trialFlag?'已审':'未审'}}</template>
            <template v-if="passStep===2">{{scope.row.retrialFlag?'已审':'未审'}}</template>
          </template>
        </el-table-column>
        <el-table-column prop="passed" label="是否入库" width="90" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            {{passedText(scope.row.passed)}}
          </template>
        </el-table-column>
        <el-table-column prop="shflText" label="职务职级层次" width="120" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="lyflText" label="来源类型" width="120" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="pysyjylxText" label="培养使用建议类型" width="160" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="ccsbsj" label="填报日期" width="150" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="操作" width="170" align="center">
          <template slot-scope="scope">
            <el-button @click="detail(scope.row)" size="mini" style="color:#000 !important;margin:10px 0 10px 5px">查看</el-button>
            <el-button v-if="$route.params.state!==2||scope.row.passed==2" @click="edit(scope.row)" type="primary" size="mini" style="margin:10px 0 10px 5px">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination style="float:right" :total="totalnum" :page-size="pageSize" @current-change="handleCurrentChange" :current-page="pageNum" @size-change="handleSizeChange" :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper"></el-pagination>
      </div>
    </section>
  </div>
</template>

<script>
import personEdit from './edit'
export default {
  components: {
    personEdit
  },
  data () {
    return {
      unWritePersons: [],
      unWritePersonIds: [],
      opinionFlag: false,
      rkyjloading: false,
      rkyjVisible: false,
      rkyjForm: {
        rkyj: ''
      },
      rkyjFormRules: {
        rkyj: [
          { required: true, message: '入库依据必填', trigger: 'change' }
        ]
      },
      orderloading: false,
      personId: 0,
      passStep: 1,
      passStepText: '初审',
      unitname: '',
      unitid: '',
      role: [],
      timestamp: '',
      listLoading: false,
      ids: [],
      tableHeight: 100,
      list: [
      ],
      pageNum: 1,
      pageSize: 20,
      totalnum: 10,
      item: {},
      dialogtitle: '新增',
      dialogVisible: false,
      readonly: false,
      total: 0,
      Isace: 'asc',
      Sortkey: '',
      changeSizeFlag: false,
      userRoles0: '', // 举报管理员权限
      totalPage: 0
    }
  },
  methods: {
    tableRowClassName ({row}) {
      if (row.isOverAge === 1) {
        return 'youngTableRowAge'
      } else {
        return ''
      }
    },
    handleClick (theYear) {
      let thePath = '/youngCadres/deptlist'
      if (this.inRoles('ROLE_admin') || this.inRoles('ROLE_sizhang') || this.inRoles('ROLE_fusizhang') || this.inRoles('ROLE_youngadmin')) {
        thePath = '/youngCadres/personlist'
      }
      return {
        path: thePath,
        query: {
          theYear
        }
      }
    },
    querySearch (queryString, cb) {
      return this.getNotice(this, queryString, cb)
    },
    getNotice (self, queryString, cb) {
      let para = {
        key: queryString
      }
      self.$http
        .post(this.$http.defaults.youngAPI + `api/busOpinion/getRecentList`, para)
        .then(function (response) {
          console.log('获取成功')
          var results = response.data.result
          let newArr = []
          results.forEach(function (item) {
            let obj = {'value': item}
            newArr.push(obj)
          })
          cb(newArr)
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    setOrder (direction) {
      if (this.ids && this.ids.length === 1) {
        let para = {personId: this.ids[0].id, direction: direction}
        this.orderloading = true
        this.$http
          .post(this.$http.defaults.youngAPI + 'api/busCandidatePerson/updateOrder', para)
          .then(response => {
            this.orderloading = false
            if (response.data.success) {
              this.getList(this.ids[0].id)
            } else {
              this.$message({
                message: '排序失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            this.orderloading = false
            console.log(error)
            this.$message({
              message: '网络排序失败:' + error,
              type: 'error'
            })
          })
      } else {
        this.$message({
          message: '请选择一条信息进行排序',
          type: 'error'
        })
      }
    },
    indexMethod (index) {
      return index + (this.pageNum - 1) * this.pageSize + 1
    },
    sendback () {
      let para = {
        id: this.unitid
      }
      if (this.ids && this.ids.length > 0) {
        para = {
          id: this.unitid,
          personIds: this.ids.map(item => item.id)
        }
      }
      let url = 'api/busUnit/saveBackward'
      this.$http
        .post(this.$http.defaults.youngAPI + url, para)
        .then(response => {
          if (response.data.success) {
            this.$message({
              message: '已退回',
              type: 'success'
            })
            this.backUnitList()
          } else {
            this.$message({
              message: '退回失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '网络退回失败:' + error,
            type: 'error'
          })
        })
    },
    passed () {
      if (this.opinionFlag || this.passStep === 2) {
        this.$http
          .get(this.$http.defaults.youngAPI + 'api/busUnit/getCheckedPersons?id=' + this.unitid)
          .then(response => {
            if (response.data.success) {
              if (response.data.result.length > 0) {
                this.unWritePersons = response.data.result.map(item => item.xm)
                this.unWritePersonIds = response.data.result.map(item => item.id)
                this.rkyjVisible = true
                this.rkyjForm.rkyj = ''
              } else {
                this.rkyjSubmit(true)
              }
            } else {
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.$message({
              message: '网络获取失败:' + error,
              type: 'error'
            })
          })
      } else {
        this.rkyjSubmit(true)
      }
    },
    rkyjSubmit (flag) {
      if (flag) {
        this.datapost()
      } else {
        this.$refs.rkyjForm.validate((valid) => {
          if (valid) {
            this.datapost()
          }
        })
      }
    },
    datapost () {
      let url = ''
      if (this.passStep === 1) {
        url = 'api/busUnit/submitToRetrial'
      }
      if (this.passStep === 2) {
        url = 'api/busUnit/updateToEnd'
      }
      this.rkyjloading = true
      this.$http
        .post(this.$http.defaults.youngAPI + url, {id: this.unitid, rkyj: this.rkyjForm.rkyj, personIds: this.unWritePersonIds})
        .then(response => {
          this.rkyjloading = false
          if (response.data.success) {
            if (response.data.result && response.data.result.length > 0) {
              this.$alert('注意：身份证号（' + response.data.result.join('、') + '）在正式库中已存在', this.passStepText + '完成', {
                confirmButtonText: '确定'
              })
            } else {
              this.$message({
                message: this.passStepText + '完成',
                type: 'success'
              })
            }
            this.backUnitList()
          } else {
            this.$message({
              message: '提交失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          this.rkyjloading = false
          console.log(error)
          this.$message({
            message: '网络提交失败:' + error,
            type: 'error'
          })
        })
    },
    formatDate (str) {
      return str.slice(0, 4) + '.' + str.slice(4, 6)
    },
    passedText (id) {
      switch (id) {
        case 1:
          return '入库'
        case 2:
          return '不入库'
      }
    },
    backUnitList () {
      this.$router.push(
        {
          name: 'youngCadresDeptList',
          params: {
            page: this.$route.params.page,
            theYear: this.$route.params.theYear
          }
        }
      )
    },
    checkyoungCadresRole () {
      if (this.inRoles('ROLE_other')) {
        this.$router.push({name: 'youngCadresDept'})
      } else if (this.inRoles('ROLE_youngadmin')) {
        this.passStep = this.$route.params.passStep
        if (this.passStep === 1) {
          this.passStepText = '初审'
        } else if (this.passStep === 2) {
          this.passStepText = '审查'
        }
      } else if (this.inRoles('ROLE_sizhang') || this.inRoles('ROLE_fusizhang') || this.inRoles('ROLE_chuzhang')) {
        this.passStep = 2
        this.passStepText = '审查'
      } else if (this.inRoles('ROLE_banshirenyuan')) {
        // 请求后端接口验证是否有青年干部初审权限
        this.passStep = 1
        this.passStepText = '初审'
      } else if (this.inRoles('ROLE_admin')) {
        this.$router.push({name: 'youngCadresPersonList'})
      }
    },
    inRoles (str) {
      let arr = this.userRoles0
      if (arr.indexOf(str) === -1) {
        return false
      } else {
        return true
      }
    },
    toggleSelection (id) {
      this.$nextTick(() => {
        if (id) {
          let newrow = this.list.find(item => item.id === id)
          console.log(newrow)
          this.$refs.multipleTable.toggleRowSelection(newrow)
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      })
    },
    handleSelectionChange (val) {
      this.ids = val
    },
    del (id) {
      let ids = []
      if (id) {
        ids = [id]
      } else {
        ids = this.ids.map(item => item.id)
      }
      if (ids.length > 0) {
        this.$http.post(this.$http.defaults.youngAPI + `api/busCandidatePerson/removePersons`, {ids: ids}).then(response => {
          if (response.data.success === true) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
          } else {
            console.log('删除失败:' + response.data.message)
            this.$message({
              message: '删除失败:' + response.data.message,
              type: 'error'
            })
          }
          this.getList()
        })
      } else {
        this.$message({
          message: '请至少选择一条信息',
          type: 'danger'
        })
      }
    },
    dialogHide (flag) {
      this.dialogVisible = false
      if (flag) {
        this.getList()
      }
    },
    edit (data) {
      this.readonly = false
      this.dialogtitle = '编辑'
      this.personId = data.id
      this.dialogVisible = true
      this.timestamp = new Date().getTime()
    },
    detail (data) {
      this.readonly = true
      this.dialogtitle = '查看'
      this.personId = data.id
      this.dialogVisible = true
      this.timestamp = new Date().getTime()
    },
    handleSizeChange (val) {
      this.changeSizeFlag = true
      this.pageNum = 1
      this.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      if (this.changeSizeFlag === false) {
        this.pageNum = val
        this.getList()
      }
    },
    // 查询
    search () {
      this.pageNum = 1
      this.getList()
    },
    // 排序
    sortChange: function (column, prop, order) {
      this.Sortkey = column.prop
      if (column.order === 'ascending') {
        this.Isace = 'asc'
      } else {
        this.Isace = 'desc'
      }
      this.getList()
    },
    getList (id) {
      let para = {
        ssdw: this.unitid,
        state: this.$route.params.state,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        orderField: 'id',
        orderType: 'desc'
      }
      this.listLoading = true
      this.$http
        .post(this.$http.defaults.youngAPI + `api/busCandidatePerson/queryPersonPage`, para)
        .then(response => {
          if (response.data.success) {
            this.listLoading = false
            this.list = response.data.result.records
            this.totalnum = response.data.result.total
            this.changeSizeFlag = false
            this.totalPage = response.data.result.pages
            if (id) {
              this.toggleSelection(id)
            }
            if (response.data.result.current > response.data.result.pages && response.data.result.pages !== 0) {
              this.pageNum = response.data.result.pages
              this.getList()
            }
          } else {
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          this.$message({
            message: '网络获取失败:' + error,
            type: 'error'
          })
        })
    },
    tableresize (obj) {
      var clientHeight = 0
      if (document.body.clientHeight && document.documentElement.clientHeight) {
        clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight
      } else {
        clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight
      }
      let myheight = 315
      obj.$nextTick(function () {
        obj.tableHeight = clientHeight - myheight
      })
    },
    getOpinionFlag () { // 初审是否需要填写入库依据，根据后台配置文件返回
      this.$http
        .get(this.$http.defaults.youngAPI + `api/busOpinion/showOpinion`)
        .then(response => {
          if (response.data.success) {
            this.opinionFlag = response.data.result
          } else {
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.$message({
            message: '网络获取失败:' + error,
            type: 'error'
          })
        })
    }
  },
  mounted () {
    this.getOpinionFlag()
    this.userRoles0 = localStorage.getItem('Roles')
    this.unitname = this.$route.params.unitname
    this.unitid = this.$route.params.id
    this.getList()
    this.checkyoungCadresRole()
    this.tableresize(this)
    window.onresize = () => {
      this.tableresize(this)
    }
  }
}
</script>
<style>
.youngTableRowAge{
  background: #FFE8E8 !important;
}
#youngcadres .el-drawer__wrapper{
  width: 100%;
  height: 100%;
  position: fixed !important;
  overflow: hidden;
}
  .wboxd .el-table th{
    font-weight: normal;
    background-image: linear-gradient(to bottom , #f8f8f8, #efefef);
  }
  .wboxd .el-table td, .el-table th{
    padding:0;
    font-size:var(--size14) !important;
    line-height: 20px;
    font-family: '宋体'
  }
  .tableth{
    background-image: linear-gradient(to bottom , #f8f8f8, #efefef);
    height:33px;
  }
  #testlist .wboxs{
    height:45px;
    padding-top:10px;
  }
  #youngcadres .el-table td{
    border-right: 1px solid #95B8E7;
    border-bottom: 1px solid #95B8E7;
  }
  #youngcadres .el-radio__label{
    font-size: var(--size14) !important;
  }
  #youngcadres .el-radio{
    margin-right:10px !important;
  }
</style>
<style scoped>
  #youngcadres .el-button{
    color:#fff !important;
  }
  #youngcadres h1{
    font-size:var(--size16) !important;
    font-weight: bolder;
    height: 30px;
    border-bottom: 1px solid #95B8E7;
    font-family: '宋体';
    line-height: 30px;
    color: #000;
    padding-left:10px;
    background-image: linear-gradient(to bottom , #EEF4FF, #E0ECFF);
    margin:0;
  }
  .el-pagination{
    float: left;
    padding:7px 10px;
  }
  #youngcadres .wboxs{
    width: 100%;
    background: #fff;
    border: 1px solid #95B8E7;
    margin:0 10px;
    overflow: hidden;
    padding:0;
  }
  .wboxd{
    padding:0;
    width: calc(100% - 0px);
    background: #fff;
    border: 1px solid #95B8E7;
    margin:0 10px;
    overflow: hidden;
  }
  .red-bold {
    color: red;
    font-weight: bold;
  }
</style>
